package com.netease.file;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @Description 文件拷贝
 * @Author bjweitingting
 * @Date 2018/10/18
 **/
public class FileCopy {
    public static void main(String[] args) {
        String src = "";
        String target = "";
        File sourceFile = new File(src);
        File targetFile = new File(target);
        method1(sourceFile, targetFile);
    }

    /**
     * 通过文件流实现
     *
     * @param sourceFile
     * @param targetFile
     */
    public static void method1(File sourceFile, File targetFile) {
        try (InputStream inputStream = new FileInputStream(sourceFile);
             OutputStream outputStream = new FileOutputStream(targetFile)) {
            byte[] bytes = new byte[1024];
            while (-1 != inputStream.read(bytes)) {
                outputStream.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过transferTo实现
     * @param sourceFile
     * @param targetFile
     */
    public static void method2(File sourceFile, File targetFile) {
        try (FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
             FileChannel targetChannel = new FileOutputStream(targetFile).getChannel()
        ) {
            for (long count = sourceChannel.size(); count > 0; ) {
                //transferred转移的数量
                long transferred = sourceChannel.transferTo(sourceChannel.position(), count, targetChannel);
                //手动设置position
                sourceChannel.position(sourceChannel.position() + transferred);
                count -= transferred;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
